package com.own.component.store.local.util;

import com.google.common.util.concurrent.RateLimiter;
import com.own.component.store.core.util.RateLimiterUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * LocalRateLimiterUtil
 *
 * @author chenxueli
 * @date 2024-04-16 15:03:00
 */
@SuppressWarnings("all")
public class LocalRateLimiterUtil implements RateLimiterUtil {

    private final Map<String, RateLimiter> LIMITER_MAP = new HashMap<>();

    /**
     * 获取RateLimiter
     *
     * @param name         名称
     * @param rate         速率
     * @param rateInterval 速率间隔
     * @param unit         单位
     */
    @Override
    public void create(String name, long rate, long rateInterval, TimeUnit unit) {
        var limiter = RateLimiter.create(1.0 * rate / rateInterval, rateInterval, unit);
        LIMITER_MAP.put(name, limiter);
    }

    /**
     * 尝试获取
     *
     * @param name 名称
     * @return 是否获取成功
     */
    @Override
    public boolean tryAcquire(String name) {
        return LIMITER_MAP.get(name).tryAcquire();
    }
}
